package com.xingchi.tornado.dict.service;

import com.xingchi.tornado.dict.enums.DictStorageTypeEnum;
import com.xingchi.tornado.dict.model.DictMetadata;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 内存存储
 *
 * @author xingchi
 * @date 2024/5/19 20:42
 */
@Slf4j
public class InMemoryDictStorageService implements DictStorageService {

    /**
     * 字典缓存
     */
    private static final Map<String, List<DictMetadata.Item>> DICT_CACHE = new ConcurrentHashMap<>();

    /**
     * 存储字典数据
     *
     * @param dictMetadataList 字典数据集合
     */
    @Override
    public void storage(List<DictMetadata> dictMetadataList) {
        for (DictMetadata dictMetadata : dictMetadataList) {
            DICT_CACHE.put(dictMetadata.getGroup(), dictMetadata.getItems());
        }
    }

    /**
     * 获取所有字典项
     *
     * @return 所有字典项
     */
    @Override
    public Map<String, List<DictMetadata.Item>> getAllDictItems() {
        return DICT_CACHE;
    }

    /**
     * 根据字典分组获取字典数据
     *
     * @param group 分组项
     * @return 字典数据
     */
    @Override
    public List<DictMetadata.Item> getDictItems(String group) {
        return DICT_CACHE.getOrDefault(group, new ArrayList<>());
    }

    /**
     * 存储类型
     *
     * @param storageType 存储类型
     * @return 是否支持
     */
    @Override
    public boolean supports(Integer storageType) {
        return DictStorageTypeEnum.IN_MEMORY.isType(storageType);
    }
}
